import { defineComponent, ref, watch } from "vue";
import { switchStore } from "../../store";
import { useScrollNumber } from "./until";
import { contains, getUUid } from "@/focus/path/until";
import "./index.less";
// 定义函数类型
export default defineComponent({
  name: "focus-scroll",
  emits: ["change"],
  model: {
    prop: "scrollTo",
    event: "change"
  },
  props: {
    scroll: {
      type: String,
      default: "y",
    },
    scrollTo: {
      type: Number,
    },
    offset: {
      type: [Number, String],
      default: "center"
    },
  },

  setup(props, { emit }) {
    const inject = switchStore.inject()
    const domRef = ref()
    const domChildRef = ref()
    const uid = ref(getUUid())
    const { scrollNo, changeScroll } = useScrollNumber({ childRef: domChildRef, parentRef: domRef }, props as any)
    watch(() => inject.state.focusId.value, (id) => {
      if (props.scrollTo != null) return
      const item = inject.state.widgetList.find(v => v.uid === id)
      if (!item || !domRef.value || !domChildRef.value) return
      //如果该元素没有在当前的scroll内，则不继续执行
      if (!(domRef.value && contains(domChildRef.value, item.ele))) return
      setTimeout(() => {
        changeScroll({
          currentEle: item.ele as HTMLElement,
          currentScroll: item.scrollNo
        })
      });
    }, { immediate: true })
    watch(() => scrollNo.value, () => {
      if (props.scrollTo == null) return
      emit("change", scrollNo.value)
    }, { immediate: true })
    watch(() => props.scrollTo, () => {
      if (props.scrollTo == null) return
      scrollNo.value = props.scrollTo
    }, { immediate: true })
    return {
      domChildRef,
      domRef,
      scrollNo,
      uid,
    }
  },
  render() {
    return (
      <div id={this.uid} ref="domRef" class="fe-scroll">
        <div class={`fe-scroll-box ${this.scroll === "y" ? "width100" : "height100"}`} ref="domChildRef" style={{
          'top': (this.scroll === 'y' ? this.scrollNo : 0) + 'px',
          'left': (this.scroll === 'x' ? this.scrollNo : 0) + 'px'
        }}>{this.$slots.default}</div>
      </div>
    );
  }
})
